//
//  InvestmentViewController.m
//  TenThousand
//
//  Created by baixue on 16/6/6.
//  Copyright © 2016年 baixue. All rights reserved.
//

#import "InvestmentViewController.h"
#import "InvestFirstCell.h"
#import "InvestOtherCell.h"
#import "investHeaderView.h"
#import "const.h"
#import "InvestListViewController.h"//定期推荐列表
#import "CurrentViewController.h"
#import "BorrowListModel.h"
#import "InvestFirstCell.h"
#import "ZhuanRangViewController.h"

#import "TransferGetListModel.h"//转让债权模型

@interface InvestmentViewController () <UITableViewDelegate,UITableViewDataSource>
{
    BOOL _isLastPage;
    NSInteger _currentPage;
}

@property (nonatomic, strong) NSMutableArray *timeDepositArrM;
@property (nonatomic, strong) NSMutableArray *timeDepositTransferArray;
@property (nonatomic, strong) investHeaderView *investHeaderV;

@end

@implementation InvestmentViewController

- (NSMutableArray *)timeDepositArrM {
    if (!_timeDepositArrM) {
        _timeDepositArrM = [NSMutableArray array];
    }
    return _timeDepositArrM;
}
- (NSMutableArray *)timeDepositTransferArray{
    if (!_timeDepositTransferArray) {
        _timeDepositTransferArray = [NSMutableArray array];
    }
    return _timeDepositTransferArray;
}

- (investHeaderView *)investHeaderV {
    if (!_investHeaderV) {
        _investHeaderV = [[investHeaderView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, 50)];
    }
    return _investHeaderV;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"投资";
    
    [self.view addSubview:self.myTableView];

    [self refresh];

}

- (void)viewWillAppear:(BOOL)animated {

    [self getTimeDepositDetailWithPage:1];
    [self getAllTimeDepositListWithPage:1];


}


//所有定期推荐列表接口
- (void)getAllTimeDepositListWithPage:(NSInteger)page{
    
    NSString *index = [NSString stringWithFormat:@"%ld",page];
    NSDictionary *dict = @{
                           @"PageIndex":index
                           };
    [self.timeDepositArrM removeAllObjects];
    [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Borrow.GetList" withParaments:dict withSuccessBlock:^(NSDictionary *object) {

        
        NSMutableArray *arr = [NSMutableArray array];
        [arr addObjectsFromArray:[object[@"Data"] firstObject][@"List"]];
        for (int i = 0 ; i < 5; i++) {
            [self.timeDepositArrM addObject:[arr objectAtIndex:i]];
            
        }
//        NSLog(@"%ld",self.timeDepositArrM.count);
        
        [self.myTableView reloadData];
    } withFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    } progress:^(float progress) {
        
    }];
}


//定期明细接口
- (void)getTimeDepositDetailWithPage:(NSInteger)page {
      NSString *index = [NSString stringWithFormat:@"%ld",page];
    NSDictionary *dict = @{
                           @"PageIndex":index
                           };
    [self.timeDepositTransferArray removeAllObjects];
    [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Transfer.GetList" withParaments:dict withSuccessBlock:^(NSDictionary *object) {

        NSMutableArray *arr = [NSMutableArray array];
        [arr addObjectsFromArray:[object[@"Data"] firstObject][@"ItemList"]];
        for (NSDictionary *dic in arr) {
            TransferGetListModel *model = [[TransferGetListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.timeDepositTransferArray addObject:model];
        }
        for (int i = 0 ; i < 5; i++) {
            [self.timeDepositTransferArray addObject:[arr objectAtIndex:i]];
        }

        
        [self.myTableView reloadData];
    } withFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    } progress:^(float progress) {
        
    }];
}


//懒加载tableView
- (UITableView *)myTableView
{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height-64) style:UITableViewStyleGrouped];
    }
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _myTableView.backgroundColor = [UIColor whiteColor];
    _myTableView.showsVerticalScrollIndicator = NO;

    return _myTableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.timeDepositArrM.count;
}


//cell复用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        
        
        //投资中
        InvestOtherCell *investOtherCell = [tableView dequeueReusableCellWithIdentifier:@"InvestOtherCell"];
        if (investOtherCell == nil) {
            investOtherCell = [[[NSBundle mainBundle]loadNibNamed:@"InvestOtherCell" owner:nil options:nil] lastObject];
        }
        
   
        if (self.timeDepositArrM.count != 0) {
            
        
            NSString *str = @"%";
            investOtherCell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            investOtherCell.titleLabel.text = [NSString stringWithFormat:@"%@%@",self.timeDepositArrM[indexPath.row][@"ProjectName"], self.timeDepositArrM[indexPath.row][@"Code"]];
            investOtherCell.termLabel.text = [NSString stringWithFormat:@"%@", self.timeDepositArrM[indexPath.row][@"Term"]];
            investOtherCell.rateLabel.text = [NSString stringWithFormat:@"%.2f", [self.timeDepositArrM[indexPath.row][@"Rate"] doubleValue]];
            investOtherCell.minAmountLabel.text = [NSString stringWithFormat:@"%.2f元起投", [self.timeDepositArrM[indexPath.row][@"MinAmount"] doubleValue]];
            investOtherCell.tenderLabel.text = [NSString stringWithFormat:@"已加入%@人", self.timeDepositArrM[indexPath.row][@"Tender"] ];
            [investOtherCell.progressView setProgress:[self.timeDepositArrM[indexPath.row][@"proportion"] floatValue]/100 animated:NO];
            investOtherCell.fasate.text = [NSString stringWithFormat:@"%@",self.timeDepositArrM[indexPath.row][@"FaSate"]];
        
        }

        if (indexPath.row ==self.timeDepositArrM.count-1) {
            investOtherCell.contentView.backgroundColor = [UIColor whiteColor];
            investOtherCell.bottomView.frame = CGRectMake(0, 0, Screen_Width, 140);
            
        }else{
            //cell添加阴影
            investOtherCell.bottomView.layer.shadowColor = [UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1.00].CGColor;
            investOtherCell.bottomView.layer.shadowOffset =CGSizeMake(0, 1);;
            investOtherCell.bottomView.layer.shadowOpacity = YES;
        }
        
        
        return investOtherCell;
    } else {
        
        
        
        InvestFirstCell *investOtherCell = [tableView dequeueReusableCellWithIdentifier:@"FIRSTCELL"];
        if (investOtherCell == nil) {
            investOtherCell = [[[NSBundle mainBundle]loadNibNamed:@"InvestFirstCell" owner:nil options:nil] lastObject];
        }
       
            investOtherCell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (self.timeDepositTransferArray.count != 0 ) {
            TransferGetListModel *model = _timeDepositTransferArray[indexPath.row];
            
            [investOtherCell setDataWithModel:model];
        }
       
            


        
        return investOtherCell;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        if (indexPath.section == 0  && indexPath.row == self.timeDepositArrM.count -1) {
            return 140;
        }
        return 150;
    }else{
        return 128;
    }
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 40;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        CurrentViewController *currentView = [[CurrentViewController alloc] init];
        [self setHidesBottomBarWhenPushed:YES];
        if (self.timeDepositArrM.count) {
            
            currentView.borrowId = self.timeDepositArrM[indexPath.row][@"BorrowId"];
            currentView.item = [NSString stringWithFormat:@"%@%@",self.timeDepositArrM[indexPath.row][@"ProjectName"],self.timeDepositArrM[indexPath.row][@"Code"]];
            currentView.percentStr = [NSString stringWithFormat:@"%@",self.timeDepositArrM[indexPath.row][@"proportion"] ];
            [self.navigationController pushViewController:currentView animated:YES];
            [self setHidesBottomBarWhenPushed:NO];

        }
       
    }else{
        //跳转到债权转让页面
        ZhuanRangViewController *payMoneyView = [[ZhuanRangViewController alloc] init];
        
        if (_timeDepositTransferArray.count) {
            TransferGetListModel *model = _timeDepositTransferArray[indexPath.row];
            payMoneyView.TransferId = model.TransferId;
            payMoneyView.Borrowid = model.Borrowid;
            payMoneyView.model = model;
            
        }
        [self setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:payMoneyView animated:YES];
        [self setHidesBottomBarWhenPushed:NO];
       
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        self.investHeaderV.titleLabel.text = @"投资中";
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TapClick:)];
        [self.investHeaderV addGestureRecognizer:tap];
        self.investHeaderV.userInteractionEnabled = YES;
    } else {
        self.investHeaderV.titleLabel.text = @"债权转让";
     
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [self.investHeaderV addGestureRecognizer:tap];
        self.investHeaderV.userInteractionEnabled = YES;
    }
    
    
    
    return self.investHeaderV;
}


//跳转到定期列表页面
-(void)TapClick:(UITapGestureRecognizer *)tap{

    

    InvestListViewController *view = [[InvestListViewController alloc] init];
    view.index = 0;
    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:view animated:YES];
    [self setHidesBottomBarWhenPushed:NO];
}

//跳转到债权转让列表页面
-(void)tapClick:(UITapGestureRecognizer *)tap{
    
    InvestListViewController *view = [[InvestListViewController alloc] init];
    view.index = 1;
    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:view animated:YES];
    [self setHidesBottomBarWhenPushed:NO];
}


//MJ刷新
-(void)refresh
{
    
    //下拉刷新
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^
                                {
                                    
                                    [self getAllTimeDepositListWithPage:1];
                                    [self getTimeDepositDetailWithPage:1 ];
                                    
                                    [self.myTableView.mj_header endRefreshing];
                                }];
//    //上拉加载
//    self.myTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//        
//        
//        
//        if (_isLastPage) {
//            [self.myTableView.mj_footer endRefreshing];
//            return;
//        }
//        
//        [self getAllTimeDepositListWithPage:_currentPage++];
//        
//        [self.myTableView.mj_footer endRefreshing];
//    }];
//    
    
}

@end
